<!-- 表格查询条件 -->

<template>
  <div class="table-filter flex q-gutter-sm">
    <!-- 日期范围条件 -->
    <template v-if="showDate">
      <q-input :model-value="dateInput" :label="dateLabel" style="min-width: 230px" hide-bottom-space dense>
        <template #append><q-icon :name="mdiCalendarMonthOutline" /></template>
        <q-menu v-model="menu">
          <q-date ref="dateRef" v-model="range" range mask="YYYY-MM-DD" @update:model-value="selectDate" />
        </q-menu>
      </q-input>
    </template>

    <!-- 其它条件插入槽 -->
    <slot v-if="!$q.screen.xs"></slot>

    <!-- 搜索框 -->
    <!-- prettier-ignore -->
    <q-input v-model="model.search" dense :placeholder="label" :style="'max-width: ' + width + 'px;min-width:100px'" clearable @keyup.enter="change" @clear="change">
      <template #after>
        <q-btn icon="search" color="primary" flat round style="margin-left:-5px" @click="change" />
      </template>
</q-input>
  </div>
</template>

<script lang="ts" setup>
  import { computed, reactive, ref } from 'vue';
  import { mdiCalendarMonthOutline } from '@quasar/extras/mdi-v7';

  const props = withDefaults(
    defineProps<{
      modelValue: {
        startDate?: Date | number | string | undefined;
        endDate?: Date | number | string | undefined;
        search?: string | undefined;
      };
      label?: string | undefined;
      width?: number | undefined;
      showDate?: boolean;
      dateLabel?: string | undefined;
    }>(),
    { label: '模糊搜索', width: 200, dateLabel: '创建时间' },
  );
  const emit = defineEmits(['change']);
  const change = () => emit('change', model);

  const model = reactive(props.modelValue);

  const menu = ref(false);
  const range = ref({ from: model.startDate, to: model.endDate });
  const dateInput = computed(() => {
    if (range.value == null || (typeof range.value === 'object' && range.value.from === undefined && range.value.to === undefined))
      return undefined;

    if (typeof range.value === 'string' && (range.value as string).toString().length === 10) {
      return range.value + ' 到 ' + range.value;
    }

    return range.value.from + ' 到 ' + range.value.to;
  });

  function selectDate(v: { from: string; to: string }) {
    if (v == null) {
      model.startDate = undefined;
      model.endDate = undefined;
    } else if (typeof v === 'string' && (v as string).length == 10) {
      model.startDate = v;
      model.endDate = v;
      menu.value = false;
      change();
    } else {
      model.startDate = v.from;
      model.endDate = v.to;
      menu.value = false;
      change();
    }
  }
</script>

<style lang="scss" scoped>
  .table-filter {
    :deep(.q-select) {
      min-width: 120px;
    }
  }
</style>
